package ru.bytedog.oiot.counter.bot.controller.rest;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.web.bind.annotation.*;
import ru.bytedog.oiot.counter.bot.bean.ErrorCode;
import ru.bytedog.oiot.counter.bot.dto.dashboard.CurrentUser;
import ru.bytedog.oiot.counter.bot.dto.dashboard.LoginData;
import ru.bytedog.oiot.counter.bot.entity.BotUser;
import ru.bytedog.oiot.counter.bot.exception.ServiceException;
import ru.bytedog.oiot.counter.bot.service.dashboard.AuthService;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private final AuthService service;
    private final SecurityContextRepository securityContextRepository =
            new HttpSessionSecurityContextRepository();

    public AuthController(AuthService service) {
        this.service = service;
    }

    @PostMapping("/otp")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void sendOtp(@RequestBody LoginData loginData) throws ServiceException {
        validate(loginData, true);
        service.sendOtpForUser(loginData.getUsername());
    }

    @PostMapping(path = "/login", consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
    public ResponseEntity<Void> authenticateUser(LoginData loginData, HttpServletRequest request, HttpServletResponse response) throws ServiceException {
        validate(loginData, false);
        service.login(loginData);
        securityContextRepository.saveContext(SecurityContextHolder.getContext(), request, response);
        return ResponseEntity.noContent().build();
    }


    private void validate(LoginData data, boolean isValidateOnlyLogin) throws ServiceException {
        if (data != null && StringUtils.isNotBlank(data.getUsername())
                && (isValidateOnlyLogin || StringUtils.isNotBlank(data.getPassword()))) {
            return;
        }
        throw new ServiceException(ErrorCode.BAD_REQUEST);
    }

}
